using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class watercs : MonoBehaviour
{
    public ComputeShader Shader;
    public Texture2D DEMMap;
    public Texture2D InitStateMap;
    int width, height,depth;
    Renderer rend;
    RenderTexture outputTextureA;
    RenderTexture outputTextureB;
    int UpdatewaterHandle;
    // Start is called before the first frame update
    void Start()
    {
        rend = GetComponent<Renderer>();

        width = DEMMap.width;
        height = DEMMap.height;
       
        outputTextureA = new RenderTexture(width, height, 0,RenderTextureFormat.ARGBFloat);
        outputTextureA.enableRandomWrite = true;
        outputTextureA.Create();
        outputTextureB = new RenderTexture(width, height, 0, RenderTextureFormat.ARGBFloat);
        outputTextureB.enableRandomWrite = true;
        outputTextureB.Create();

        
        transform.localScale =new Vector3(width / height, 1, 1);

        UpdatewaterHandle = Shader.FindKernel("FloodMapUpdateCS");


        ComputeBuffer cb =new ComputeBuffer(10,sizeof(float),ComputeBufferType.Constant);
        cb.SetData(new float[] { 1.0f, 1.3f, 9.8f, 5.0f, 0.00001f, 0.02f, 9.8f, 9.8f, 1.0f, 1.0f });
        Shader.SetConstantBuffer("cbFixed", cb, 0, sizeof(float) * 10);
        Shader.SetFloat("dt", 0.01f);
        Shader.SetTexture(UpdatewaterHandle, "gHeightMap", DEMMap);
        Shader.SetTexture(UpdatewaterHandle, "gWaterMapIn", InitStateMap);
        Shader.SetTexture(UpdatewaterHandle, "gWaterMapOut", outputTextureA);

        rend.material.SetTexture("_MainTex", outputTextureA);

        Shader.Dispatch(UpdatewaterHandle, width / 8, height / 8, 1);

        //Shader.SetTexture(UpdatewaterHandle, "gWaterMapIn", outputTextureA);
        //Shader.SetTexture(UpdatewaterHandle, "gWaterMapOut", outputTextureB);
        //Shader.Dispatch(UpdatewaterHandle, width / 8, height / 8, 1);

        //Shader.SetTexture(UpdatewaterHandle, "gWaterMapIn", outputTextureB);
        //Shader.SetTexture(UpdatewaterHandle, "gWaterMapOut", outputTextureA);
        //Shader.Dispatch(UpdatewaterHandle, width / 8, height / 8, 1);
    }
    // Update is called once per frame
    void Update()
    {
        //if (flag)
        //{
        //    flag = !flag;
        //    Shader.SetTexture(UpdatewaterHandle, "Result", outputTextureA);
        //    Shader.SetTexture(UpdatewaterHandle, "WaterMapIn", InitStateMap);
        //}
        //else
        //{

        //}
        Shader.SetTexture(UpdatewaterHandle, "gWaterMapIn", outputTextureA);
        Shader.SetTexture(UpdatewaterHandle, "gWaterMapOut", outputTextureB);
        Shader.Dispatch(UpdatewaterHandle, width / 8, height / 8, 1);

        Shader.SetTexture(UpdatewaterHandle, "gWaterMapIn", outputTextureB);
        Shader.SetTexture(UpdatewaterHandle, "gWaterMapOut", outputTextureA);
        Shader.Dispatch(UpdatewaterHandle, width / 8, height / 8, 1);
    }
}
